package com.xyhuo.leetcode.december;

/**
 * 螺旋矩阵Ⅱ
 * https://leetcode.cn/problems/spiral-matrix-ii/
 *
 * @time 2023/12/25
 */
public class GenerateMatrix {

//    public static void main(String[] args) {
//        GenerateMatrix gm = new GenerateMatrix();
//        gm.generateMatrix(3);
//    }

    public int[][] generateMatrix(int n) {
        this.n = n;
        int[][] ans = new int[n][n];
        int step = n % 2 == 0 ? n / 2 : n / 2 + 1;
        int val = 1;
        for (int i = 0; i < step; i++) {
            val = loop(ans, val, i);
        }
        return ans;
    }

    private int n;

    private int loop(int[][] ans, int val, int step) {
        if (n % 2 == 1 && step == n / 2) {
            ans[step][step] = val++;
        }

        for (int i = step; i < n - 1 - step; i++) {
            ans[step][i] = val++;
        }

        for (int i = step; i < n - 1 - step; i++) {
            ans[i][n - 1 - step] = val++;
        }

        for (int i = n - 1 - step; i > step; i--) {
            ans[n - 1 - step][i] = val++;
        }
        for (int i = n - 1 - step; i > step; i--) {
            ans[i][step] = val++;
        }
        return val;
    }
}
